import {defineStore} from 'pinia'
import {ref} from 'vue'

export interface head {
    name?: string,
    path?: string,
    isActive?: boolean,
    isMenu?: boolean | true
}

export const menuStore = defineStore('menuStore', () => {
    const menuIndex = ref<number>(0) //菜单栏的索引
    const headBread = ref<head[]>([]) //面包屑

    /**
     * 添加面包屑
     * @param item
     */
    const addHeadBreadItem = (item: head) => {
        // 先将所有项设为非激活状态
        headBread.value.forEach(existing => existing.isActive = false)

        const existingIndex = headBread.value.findIndex(existing => existing.name === item.name)
        if (existingIndex === -1) {
            // 如果不存在，添加新项
            headBread.value.push({...item, isActive: true})
        } else {
            // 如果存在，激活该项
            headBread.value[existingIndex].isActive = true
        }
    }

    /**
     * 删除面包屑
     * @param name
     */
    const deleteHeadBreadItem = (name: string) => {
        const targetIndex = headBread.value.findIndex(item => item.name === name)
        if (targetIndex === -1) return

        // 如果删除的是激活项，需要激活其他项
        const isActiveItem = headBread.value[targetIndex].isActive

        // 使用splice删除，保持响应式
        headBread.value.splice(targetIndex, 1)

        // 如果删除的是激活项且还有其他项，激活下一个或上一个
        if (isActiveItem && headBread.value.length > 0) {
            let nextActiveIndex = targetIndex >= headBread.value.length ? headBread.value.length - 1 : targetIndex
            headBread.value[nextActiveIndex].isActive = true
            return headBread.value[nextActiveIndex] // 返回新激活的项，用于路由跳转
        }

        return null
    }

    /**
     * 设置激活的面包屑
     * @param name
     */
    const setActiveHeadBreadItem = (name: string) => {
        headBread.value.forEach(item => {
            item.isActive = item.name === name
        })
    }

    return {
        menuIndex,
        headBread,
        addHeadBreadItem,
        deleteHeadBreadItem,
        setActiveHeadBreadItem
    }
})